/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fwdisp;

import ch.ubique.inieditor.IniEditor;
import fwdisp.elements.Label;
import fwdisp.elements.StatusLabel;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; 
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import settings.MainSettingsManager;
import settings.collections.AusrueckordnungCollection;
import settings.collections.CarCollection;
import settings.collections.elements.AusrueckOrdnung;
import settings.collections.elements.Car;
import settings.collections.elements.EType;
import settings.collections.elements.Schleife;



/**
 *
 * @author rbs
 */
public class MainFrame{

    
    private ArrayList<Car> cars; 
    private ArrayList<Schleife> schleifen;
    private ArrayList<EType> eTypes;
    //private ArrayList<AusrueckOrdnung> aROs;
        
    //Der Frame selbst:
    private JFrame frame;
    //Die enthaltenen Elemente:
    private fwdisp.elements.Label e_typ;
    private Label e_txt;
    private fwdisp.elements.Label e_ort;
    private fwdisp.elements.Label e_nr;
    private fwdisp.elements.Label e_typ_name;
    private fwdisp.elements.Label e_txt_name;
    private fwdisp.elements.Label e_ort_name;
    private fwdisp.elements.Label e_nr_name;
    private fwdisp.elements.Label big_label;

    private fwdisp.elements.CountDownLabel countdown;

    private  fwdisp.elements.Label e_art;
    private  fwdisp.elements.Label[] schleifen_label;

    private JLabel status_bg;

    private StatusLabel[] car_label; 

    private JPanel carPanel;
    private JButton end;
    private JButton debugbut;
    private int[] fahrzeugStatus;
    //TODO: init with 0

    private String eTyp = "Einsatz";

    private boolean[] schleifen_stat = new boolean[7];

    private Logger logger;


    public MainFrame()
    {
        cars = MainSettingsManager.getSetting().getCarCollection().getCars();
        schleifen = MainSettingsManager.getSetting().getSchleifenCollection().getSchleifen();
        eTypes = MainSettingsManager.getSetting().geteTypeCollection().getETypes();
        
        car_label = new StatusLabel[cars.size()];
        fahrzeugStatus = new int[cars.size()];
        schleifen_label = new Label[schleifen.size()];
        
        logger = Logger.getLogger(Main.class.toString());
        logger.log(Level.INFO, "Frame wird initialisiert");
        frame = new JFrame("FW Display");
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
        frame.setUndecorated(true);
        frame.getContentPane().setLayout(null);
        frame.setAlwaysOnTop(true);

        e_typ_name = new Label(this);
        e_typ = new Label(this);
        e_ort_name = new Label(this);
        e_ort = new Label(this);
        e_txt_name = new Label("E-Art:", this);
        e_txt = new Label(this);
        e_nr = new Label(this);
        status_bg = new Label(this);
        e_art = new Label(this);
        //countdown = new fwdisp.content.CountDownLabel(this, "Ende in", time_ms)


        for(int i = 0; i < cars.size(); i++)
        {
            car_label[i] = new StatusLabel(this);
        }

        for(int i = 0; i < schleifen.size(); i++)
        {
            schleifen_label[i] = new Label(this);
        }
        
        carPanel = new JPanel();
        
        end = new JButton("Ende");
        debugbut = new JButton("DEBUG: ELW Status 3");
    }
    public int getWidth()
    {
        return frame.getWidth();
    }

    public int getHeigth()
    {
        return frame.getHeight();
    }

    //Returns one percent of the height:
    public int getPercHeight()
    {
        return frame.getHeight()/100;
    }

    public void showBigLabel(String text)
    {
        logger.log(Level.FINE, "Zeige ABBRUCH-FRAME");
        big_label = new Label("<html><p align=center>" + text, this);
        frame.add(big_label);
        big_label.setLocation(0, 0);
        big_label.setSize(getWidth(), getHeigth());
        big_label.setOpaque(true);
        big_label.setBackground(Color.green);
        big_label.setAlignment(Label.CENTER);
        big_label.setFont(new Font("serif", Font.BOLD, 120));
    }

    public void SetIniSettings() throws IOException
    {
        logger.log(Level.FINE, "Lade Einstellungen von ini");
        e_typ.readSettings("settings.ini", "e-typ");
        e_typ.setLocation(0, getPercHeight() * 22);
        e_typ.setHorizontalAlignment(JLabel.CENTER);
        e_typ.setBorder(Color.LIGHT_GRAY, 1); 
        
        e_ort.readSettings("settings.ini", "e-ort");
        e_ort.setLocation(0, getPercHeight() * 36  );
        e_ort.setHorizontalAlignment(JLabel.CENTER);
        e_ort.setBorder(Color.LIGHT_GRAY, 1);

        e_txt.readSettings("settings.ini", "e-txt");
        e_txt.setLocation(0, getPercHeight() * 62  );
        e_txt.setHorizontalAlignment(JLabel.CENTER);
        e_txt.setBorder(Color.LIGHT_GRAY, 1);

        e_nr.readSettings("settings.ini", "enr");
        e_nr.setLocation(0, getHeigth() - 40); 
        e_nr.setHorizontalAlignment(JLabel.LEFT);
        e_nr.setOpaque(false);

        e_art.setLocation(0, 0);
        e_art.setSize(getWidth(), 60);
        e_art.setText(eTyp);
        e_art.setHorizontalAlignment(JLabel.CENTER);
        e_art.setBackground(new Color(100, 170, 80));
        e_art.setForeground(Color.WHITE);
        e_art.setFont(new Font("Arial", Font.BOLD, 26 ));
        e_art.setBorder(Color.LIGHT_GRAY, 1);

        logger.log(Level.FINE, "Lade status- und schleifen-Einstellungen");
        
        
        IniEditor iniEditor = new IniEditor("settings.ini");
        iniEditor.load("settings.ini");
        String get = iniEditor.get("status", "dualCar");
        
       
        if (true) //TODO: read from ini
        {
            int size = cars.size();
            int list = (int) Math.ceil(size/2.0);
            carPanel = new JPanel(new GridLayout(2, list, 2, 2));
        }
        else
            carPanel = new JPanel(new GridLayout(1, 1, 2, 2));
       
        carPanel.setBackground(frame.getBackground());
        carPanel.setBounds(0, getPercHeight()*90, getWidth(), 100);

        for(Car car: cars)
        {
            int i = car.getId();
            car_label[i].setText(car.getName());
            //car_label[i].setLocation((getWidth() / cars.size()) * i ,  getPercHeight()*90);
            //car_label[i].SetWidth((int)(getWidth()/ cars.size()));
            car_label[i].readSettings("settings.ini", "Status");
            car_label[i].setHorizontalAlignment(JLabel.CENTER);
            carPanel.add(car_label[i]);
        }
        
        for(Schleife schleife: schleifen)
        { 
            int i = schleife.getId();
            if (i == schleifen.size())
                schleifen_label[i].setSize(getWidth() - ((schleifen.size()-1)*(getWidth()/schleifen.size())), 80);
            else 
                schleifen_label[i].setSize(getWidth()/schleifen.size(), 80);
            schleifen_label[i].setText(schleife.getName());
            schleifen_label[i].setLocation((getWidth()/schleifen.size())*i, 60);
            schleifen_label[i].setHorizontalAlignment(JLabel.CENTER);
            if(schleifen_stat[i])
            {
                schleifen_label[i].setBackground(new Color(100, 170, 80));
                schleifen_label[i].setForeground(Color.WHITE);
                schleifen_label[i].setFont(new Font("Arial", Font.BOLD, 22));
            }
            else
            {
                schleifen_label[i].setBackground(Color.darkGray);
                schleifen_label[i].setForeground(Color.gray);
                schleifen_label[i].setFont(new Font("Arial", Font.PLAIN, 22));
            }

            schleifen_label[i].setOpaque(true);
        }

 }

    public void SetTexts(String type, String ort, String art, int nr)
    {
        e_typ.setText(type);
 
        e_ort.setText("<html><p align=center>" + ort);
 
        e_txt.setText("<html><p align=center>" + art);
        
        String text;
        if (nr != -1)
            text = "ENR: " + nr;
        else
            text = "";
        
        Calendar calendar = new GregorianCalendar();
        e_nr.setText(text +  "   Alarmierungszeit: " + calendar.get( Calendar.HOUR_OF_DAY)
                + ":" + calendar.get(Calendar.MINUTE) + ":"
                + calendar.get(Calendar.SECOND));
    } 

    public void drawButtons(boolean debug)
    {
        logger.log(Level.FINE, "Zeichne Buttons");
        ActionListener aktion = new ActionListener() {
           public void actionPerformed(ActionEvent e){
                try {
                    update();
                } catch (InterruptedException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.exit(0);
            }
        };
                
        end.addActionListener(aktion);
        end.setSize(100, 30);
        end.setLocation(getWidth() - 120, getHeigth() - 50);
        end.setForeground(Color.blue);
        
        
        ActionListener debugaktion = new ActionListener() {
                public void actionPerformed(ActionEvent e){
                        SetStatusColor(0, Color.black, Color.green);
                        debugbut.setForeground(Color.green);
                }
        };
        
        debugbut.addActionListener(debugaktion);
        debugbut.setSize(160, 30);
        debugbut.setLocation(getWidth() - 340, getHeigth() - 50);
        debugbut.setForeground(Color.red);

    }

    private void update() throws IOException, InterruptedException
    {
        frame.setVisible(false);
        IniEditor reader = new IniEditor();
        reader.load("settings.ini");
        if (reader.get("updates", "mode").equals("after")) {
            Process proc = Runtime.getRuntime().exec("java -jar Updater.jar auto");
            proc.waitFor();
            System.exit(0);
        }
    }
    /**
     *
     * @param n_e_ort_x X-Pos von E-ORT-Beschriftung
     * @param n_e_ort_y Y-Pos von E-ORT-Beschriftung
     * @param e_ort_x   X-Pos von E-ORT
     * @param e_ort_y   Y-Pos von E-ORT
     * @param e_art_x   X-Pos von E-ART
     * @param e_art_y   Y-Pos von E-ART
     * @param e_nr_x    X-Pos von E-NR
     * @param e_nr_y    Y-Pos von E-NR
     * @param end_x     X-Pos von Button
     * @param end_y     Y-Pos von Button
     */
    public void SetPositions(int n_e_ort_x, int n_e_ort_y, int e_ort_x, 
            int e_ort_y, int e_art_x, int e_art_y, int e_nr_x,  int e_nr_y,
            int end_x, int end_y)
    {
        e_ort_name.setLocation(n_e_ort_x, getPercHeight() * n_e_ort_y);
        e_ort.setLocation(e_ort_x, getPercHeight() * e_ort_y);
        e_txt.setLocation(e_art_x, getPercHeight() * e_art_y);
        e_nr.setLocation(e_nr_x, getPercHeight() * e_nr_y);
        end.setLocation(end_x, end_y);
    }

    public void draw()
    {
        //Einsatzort-name:
       // frame.add(e_typ_name);
        e_typ_name.setOpaque(true);
        frame.add(e_typ);
        e_typ.setOpaque(true);
        //frame.add(e_ort_name);
        e_ort_name.setOpaque(true);
        //frame.add(e_txt_name);
        e_txt_name.setOpaque(true);
        frame.add(e_ort);
        e_ort.setOpaque(true);
        frame.add(e_txt);
        e_txt.setOpaque(true);
        // frame.add(e_nr);
        e_nr.setOpaque(true);
        frame.add(e_art);
        e_art.setOpaque(true);

        frame.add(end);
        end.setOpaque(true);
        
        frame.add(carPanel);

        for (int i = 0; i < schleifen.size(); i++)
        {
            frame.add(schleifen_label[i]);
            //schleifen[i].setOpaque(true);
        }


        ActionListener aktion = new ActionListener() {
                        public void actionPerformed(ActionEvent e){
                                System.exit(0);
                        }
        };


       
    }

    public void SetStatusColor(int car, Color fg, Color bg)
    {
        car_label[car].setForeground(fg);
        car_label[car].setBackground(bg);
    }

    public void SetStatusBorder(int car, boolean activ)
    {
        if (activ)
            car_label[car].setBorder(Color.black, 3);
        else
            car_label[car].setBorder(Color.black, 1);
    }

    public void SetStatusColors(int type_id)
    {
        for (Car car: cars)
                car_label[car.getId()].SetStatusInactive();
            
        AusrueckordnungCollection ausrueckordnungCollection = MainSettingsManager.getSetting().getAusrueckordnungCollection();
        AusrueckOrdnung aRO = ausrueckordnungCollection.getARO(type_id);

        if (aRO != null)
        {
            CarCollection alerted_cars = aRO.getCarCollection();
            for (Car car : cars)
                if (alerted_cars.getCar(car.getId()) != null ) 
                    {
                        car_label[car.getId()].SetStatus2();
                    }
        }
        else
            System.out.println("No ARO found:( ");
            
        
    }

    public void SetExitMsg(String msg)
    {
        e_nr.setText(e_nr.getText() + "       " + msg);
    }

    public void SetBgColor(AusrueckOrdnung ordnung)
    {
        if (ordnung == null)
            frame.getContentPane().setBackground(Color.BLUE);
        else
            frame.getContentPane().setBackground(ordnung.getEType().getBack());
    }

    public void SetRICs(String input)
    {
        if (input.charAt(input.length() - 1) == 'A')
            eTyp = "Einsatz A";
        else if(input.charAt(input.length() - 1) == 'B')
            eTyp = "Einsatz B";
        else //=='X'
            eTyp = "Einsatz";
        
        
        
        for(Schleife schleife : schleifen)
        {
            if(input.charAt(schleife.getId()) == '0')
                schleifen_stat[schleife.getId()] = false;
            else
                schleifen_stat[schleife.getId()] = true;

        }
    }

    public void addCountDown(String str, int time_ms)
    {
        countdown = new fwdisp.elements.CountDownLabel(this, str, time_ms);
        countdown.setLocation((int) (frame.getWidth() * 0.6), frame.getHeight() - 20);
        countdown.setSize(150, 100);
        countdown.setVisible(true);
        countdown.setOpaque(true);
        countdown.run(); 

        frame.add(countdown);
        
    }

    void SetTypPicture(AusrueckOrdnung ordnung)
    {
        int id = MainSettingsManager.getSetting().getAusrueckordnungCollection().getARO(ordnung.getId()).getEType().getId();
            e_typ.SetLabelIcon(MainSettingsManager.getSetting().geteTypeCollection().getEType(id).getPic().getAbsolutePath());
    }

    void setVisible(boolean b) {
        frame.setVisible(b);
    }
}
